import axios from "axios";
import { Message } from "element-ui";
import { MessageBox } from 'element-ui';
import $Store from '@/store'
import $Router from '../router'
import $Tool from '@/utils/tool'
import $Plugin from "@/utils/plugin";
const request = axios.create({
    baseURL: "/api"
})



let ErrorMes = (mes) => {
    Message({
        type: 'error',
        message: mes,
        duration: 700,
    })
}


request.interceptors.request.use(
    success => {

        let token = $Store.state.token
        if (token) {
            success.headers.Authorization = 'Bearer' + token
        }
        return success
    }, error => {
        if (axios.isCancel(error)) {
            console.error('Request cancel:' + error.message);
        } else {
            console.error(error.message);
        }
    }
)

let handGoLogin = () => {
    $Tool.removeStorage('token')
    $Router.push({ path: '/login' })
}



request.interceptors.response.use(
    success => {

        let token = success.headers['refresh-token']
        if (token) {
            $Store.commit('changeToken', token)
        }

        let { code, mes } = success.data
        if (code == 200) {
            if (mes != "ok")
                Message.success(mes)
        } else {
            if (code == 408) {
                handGoLogin()
            } else if (code == 409) {
                $Plugin.confirm(MessageBox.confirm, "登录状态过期,您可以继续留在该页面,或者重新登录", handGoLogin)
                return success.data
            } else if (code == 420) {
                $Plugin.confirm(MessageBox.confirm, "用户离线超时,您可以继续留在该页面,或者重新登录", handGoLogin)
                return success.data
            }

            if (mes != 'fail') {
                ErrorMes(mes)
            }
        }
        return success.data
    },

    error => {
        let { message, code } = error
        if (code == 'ERR_NETWORK') {
            ErrorMes("网络❌,请检查网络!连接")
        } else if (code == 'ERR_BAD_RESPONSE') {
            ErrorMes('错误响应500,服务器错误!')
        } else if (code == "ERR_BAD_REQUEST") {
            ErrorMes('错误请求400,客户端请求错误!')
        } else {
            ErrorMes(message)
        }
        return error
    }
);



export default request;